package cn.pli.bike.model;



import java.util.concurrent.TimeUnit;

import cn.pli.bike.bean.HttpResult;
import cn.pli.bike.model.http.ApiException;
import cn.pli.bike.url.API;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by shangdongzhou on 2017/8/1.
 */

public class BaseModel {
    private static final int DEFAULT_TIMEOUT=10;
    private Retrofit retrofit;
    private Object service;

    public BaseModel(Class service) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(API.URL.BASE_URL)
                .build();
        service = (Class) retrofit.create(service);
    }
    protected  <T> void toSubscribe(Observable<T> observable, final Subscriber<T> subscriber){
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     */
    protected HttpResult handlerHttpResult(HttpResult httpResult){
            if (httpResult.getCode() != 200) {
                throw new ApiException(httpResult.getCode(),httpResult.getMsg());
            }
            return httpResult;

    }


}
